#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright © 2016 lizongzhe
#
# Distributed under terms of the MIT license.
import urllib
from selenium.webdriver import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
import logging
from esr_parser.core import get_item_id
from esr_parser.exceptions import PageEndError
from esr_parser.utils import func
import re
import requests
import time
from esr_parser.models import RankingScreenShot
logger = logging.getLogger(__name__)


class Order(object):
    general = 'default'
    sales = 'sale-desc'
    credit = 'credit-desc'
    pricing_desc = 'price-desc'
    pricing_asc = 'price-asc'
    popular = 'renqi-desc'  # cn only
    total_price_desc = 'total-desc'  # cn only
    total_price_asc = 'total-asc'


class Rank_Task(object):
    driver = None

    def __init__(self, driver, keyword, order_by='general', tm_only=False, limit=604):
        self.keyword = keyword
        self.limit = limit
        self.driver = driver
        self.order_by = getattr(Order, order_by)
        self.tm_only = tm_only
        self.name = u"pc_{}_{}_{}".format(keyword, order_by, tm_only)

    @func.auto_retry(3)
    def process(self):
        keyword = self.keyword
        result_items = []
        result_right_items = []
        result_bottom_items = []
        retry = 0
        self.search_items()
        while len(result_items) < self.limit:
            self.load_page()
            meta = {"page_num": self.get_current_page()}

#            if meta['page_num'] in [1, 2]:
#                name = self.name
#                screenshot = self.driver.get_screenshot_as_png()
#                RankingScreenShot.create(name=name, screenshot=screenshot, page=int(meta['page_num']))

            items, right_items, bottom_items = self.parse_page(meta)
            result_items += items
            result_right_items += right_items
            result_bottom_items += bottom_items
            try:
                self.next_page()
            except PageEndError:
                break
        return result_items, result_right_items, result_bottom_items

    search_page = 'https://s.taobao.com/search?q={}&sort={}&filter_tianmao={}&cd=false'

    @func.auto_retry(3)
    def search_items(self):
        logger.debug('start search items')
        if self.tm_only:
            tm_only = 'tmall'
        else:
            tm_only = ''

        page_url = self.search_page.format(urllib.quote_plus(
            self.keyword.encode('utf-8')), self.order_by, tm_only)
        print page_url
        self.driver.get(page_url)
        print 'driver:', self.driver.current_url

    def next_page(self):
        print 'next page'
        curr_page, end = self.driver.find_elements_by_css_selector('.pager')[
            0].text.split('/')
        if int(curr_page) >= int(end):
            raise PageEndError()
        current_page = self.get_current_page()
        next_page = current_page + 1
        logger.debug('start next page {}'.format(next_page))
        page = self.get_current_page()

        self.driver.find_elements_by_css_selector(
            '.icon-btn-next-2')[0].click()
        WebDriverWait(self.driver, 5).until(
            lambda x: self.get_current_page() == next_page)

    @func.auto_retry(3)
    def get_current_page(self):
        page = self.driver.find_element_by_css_selector('.pager .current').text
        return int(page)

    @func.auto_retry(3)
    def load_page(self):
        logger.debug('start load page')
        driver = self.driver
        foot_elem = driver.find_element_by_css_selector('#srp-footer')
        # scroll down
        actions = ActionChains(driver)
        actions.move_to_element(foot_elem)
        actions.perform()
        actions.move_to_element(foot_elem)
        actions.perform()
        WebDriverWait(self.driver, 5).until(lambda x: len(
            x.find_elements_by_css_selector('#J_shopkeeper_bottom [class*=-item]')) > 1)

    @func.auto_retry(3)
    def parse_page(self, meta={}):
        logger.debug('parse page')
        driver = self.driver
        for i in xrange(3):
            try:

                main_items = driver.find_elements_by_css_selector(
                    '.m-itemlist .grid .items .item')
                right_items = driver.find_elements_by_css_selector(
                    '#mainsrp-p4pRight [class*=-item]')
                bottom_items = driver.find_elements_by_css_selector(
                    '#mainsrp-p4pBottom [class*=-item]')
                items = self.parse_items(main_items, meta)
                right_items = self.parse_ad_items(right_items, meta)
                bottom_items = self.parse_ad_items(bottom_items, meta)
                return items, right_items, bottom_items
            except Exception as e:
                print "parse item", e
                time.sleep(1)

    @func.auto_retry(3)
    def parse_items(self, items, meta={}):
        result = []
        for index, item in enumerate(items):
            item_info = {}
            if 'activity-tpl-banner' in item.get_attribute('class'):
                item_info['is_tm'] = None
                item_info['page_set'] = index
                item_info['pro_url'] = item.find_element_by_css_selector(
                    'a').get_attribute('href')
                try:
                    item_info['auction_num_id'] = get_item_id(item_info['pro_url'])
                except:
                    item_info['auction_num_id'] = None
                item_info['month_pays'] = None
                item_info['price'] = None
                item_info['pro_img_url'] = item.find_element_by_css_selector(
                    '.banner-img').get_attribute('data-src')
                item_info['pro_name'] = ''
                item_info['extension_type'] = 2
            elif 'activity' in item.get_attribute('class'):
                item_info['is_tm'] = None
                item_info['page_set'] = index
                item_info['auction_num_id'] = None
                item_info['month_pays'] = None
                item_info['price'] = None
                item_info['pro_url'] = item.find_element_by_css_selector(
                    'a').get_attribute('href')
                item_info['pro_img_url'] = item.find_element_by_css_selector(
                    'img.J_ItemPic').get_attribute('data-src')
                item_info['pro_name'] = item.find_element_by_css_selector(
                    '.activity-top-box').text
                item_info['extension_type'] = 2
            else:
                item_info['is_tm'] = bool(
                    item.find_elements_by_css_selector('.icon-service-tianmao'))
                item_info['page_set'] = index
                item_info['month_pays'] = item.find_element_by_css_selector(
                    '.deal-cnt').text.strip()
                if item_info['month_pays']:
                    item_info['month_pays'] = re.search('\d+', item_info['month_pays']).group()
                else:
                    item_info['month_pays'] = 0
                item_info['price'] = item.find_element_by_css_selector(
                    '.g_price strong').text
                item_info['pro_url'] = item.find_element_by_css_selector(
                    'a.J_ItemPicA').get_attribute('href')
                item_info['pro_name'] = item.find_element_by_css_selector(
                    '.title').text
                item_info['pro_img_url'] = item.find_element_by_css_selector(
                    '.J_ItemPic.img').get_attribute('data-src')
                item_info['shop_name'] = item.find_element_by_css_selector(
                    '.shopname').text

                if bool(item.find_elements_by_css_selector('.icon-service-remai')):
                    item_info['extension_type'] = 1
                else:
                    item_info['extension_type'] = 0

                try:
                    item_id = item.find_element_by_css_selector('[data-nid]').get_attribute('data-nid')
                    item_info['auction_num_id'] = item_id
                except:
                    item_info['auction_num_id'] = None

            item_info.update(meta)
            result.append(item_info)
        return result

    def parse_ad_items(self, items, meta={}):
        result = []
        for index, item in enumerate(items):
            item_info = {}
            item_info['page_set'] = index
            item_info['auction_num_id'] = ""
            try:
                item_info['month_pays'] = item.find_element_by_css_selector(
                    '[class*=-sell] em').text
            except:
                item_info['month_pays'] = 0
            
            item_info['price'] = item.find_element_by_css_selector(
                '[class*=-price]').text
            item_info['price'] = re.search('\d+\.\d+', item_info['price']).group()
            item_info['pro_url'] = item.find_element_by_css_selector(
                '[class*=-imgwrap] a').get_attribute('href')
            resp = requests.get(item_info['pro_url'], allow_redirects=False)
            item_info['auction_num_id'] = get_item_id(resp.headers.get('Location'))
            item_info['pro_name'] = item.find_element_by_css_selector('[class*=-imglink]').get_attribute('title')
            item_info['pro_img_url'] = item.find_element_by_css_selector(
                '[class*=-imgwrap] img').get_attribute('src')
            item_info.update(meta)
            result.append(item_info)
        return result
